<?php

namespace App\Http\Controllers;

use App\Services\NewsService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;

class NewsController extends BaseController {

    /**
     * 新闻资讯
     */
    public function index(Request $request) {
        return view('news.index', $this->view_data);
    }

    public function list(Request $request) {
        $params = $request->all();

        $list = (new NewsService())->getList($params);

        return $this->apiSuccess($list);
    }

    public function create(Request $request) {
        $info_id = $request->get('info_id', 0);
        $info = [];
        if (!empty($info_id)){
            $info = (new NewsService())->info($info_id);
            $info['images'] =  json_decode($info['images'], true);
        }
        $this->view_data['info'] = $info;
        return view('news.add', $this->view_data);
    }

    public function save(Request $request) {
        $data = $request->all();
        $roules = [
            'title' => 'required|max:150',
            'content' => 'required',
            'images' => 'required|json',
        ];
        $message = [
            'title.required' => '请填写标题',
            'title.max' => '标题长度不能超过100个字',
            'content.required' => '请填写内容',
            'images.required' => '请上传至少一张图片',
            'images.json' => '请上传至少一张图片',
        ];
        $validator = Validator::make($request->post(), $roules, $message);
        if ($validator->fails()) {
            $error_msg = $validator->errors()->first();
            return $this->apiError($error_msg, 1);
        }
        $info_id = data_get($data, 'info_id', 0);
        if ((new NewsService())->save($data, $info_id)){
            return $this->apiSuccess('', '保存成功');
        }
        return $this->apiError('保存失败', 100);
    }

    public function delete(Request $request) {
        $info_id = $request->get("info_id", 0);

        (new NewsService())->delete($info_id);

        return $this->apiSuccess('', '删除成功');
    }

    /**
     * 社会责任
     */
    public function sh_index(Request $request) {
        return view('shzr.index', $this->view_data);
    }

}